package de.baumann.browser.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import de.baumann.browser.R
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.utils.web3j.BalanceTask
import de.baumann.browser.utils.web3j.OdinWallet

class OcWalletListAdapter(var context: Context, var itemClickListener: RvItemClickListener) : RecyclerView.Adapter<OcWalletListAdapter.WalletViewHolder>() {

    var odinWallets: ArrayList<ETHWallet>? = null
        set(value) {
            field = value
            if (value != null) {
                notifyDataSetChanged()
            }
        }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WalletViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_wallet, parent, false)
        return WalletViewHolder(view)
    }

    override fun getItemCount(): Int {
        return if (odinWallets == null) {
            0
        } else {
            odinWallets!!.size
        }
    }

    override fun onBindViewHolder(holder: WalletViewHolder, position: Int) {
        var address = odinWallets!![position].address
        if (address.startsWith("0")) {
            address = "od${address.substring(1)}"
        }
        holder.tvWalletName.text = odinWallets!![position].name
        holder.tvWalletAddress.text = address
        BalanceTask(holder.itemTvBalance).execute(odinWallets!![position].address)
    }


    inner class WalletViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvWalletName: TextView = itemView.findViewById(R.id.tvWalletName)
        var tvWalletAddress: TextView = itemView.findViewById(R.id.tvWalletAddress)
        var ivDeafult: ImageView = itemView.findViewById(R.id.ivDeafult)
        var itemTvBalance: TextView = itemView.findViewById(R.id.itemTvBalance)

        init {
            itemView.setOnClickListener {
                itemClickListener.onClick(layoutPosition)
            }
        }
    }
}